import axios from './axios';
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

// 定义基础响应类型
interface BaseResponse<T = any> {
  code: number;
  data: T;
  message: string;
}

// 定义请求工具类
class RequestTool {
  /**
   * GET请求
   * @param url 请求地址
   * @param params 查询参数
   * @param config 额外配置
   */
  get<T = any>(
    url: string,
    params?: Record<string, any>,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return axios.get(url, { params, ...config })
      .then((response: AxiosResponse<BaseResponse<T>>) => {
        return response.data.data;
      })
      .catch((error: AxiosError) => {
        console.error('GET request failed:', error);
        throw error;
      });
  }

  /**
   * POST请求
   * @param url 请求地址
   * @param data 请求体数据
   * @param config 额外配置
   */
  post<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return axios.post(url, data, config)
      .then((response: AxiosResponse<BaseResponse<T>>) => response.data.data)
      .catch((error: AxiosError) => {
        console.error('POST request failed:', error);
        throw error;
      });
  }

  /**
   * PUT请求
   * @param url 请求地址
   * @param data 请求体数据
   * @param config 额外配置
   */
  put<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return axios.put(url, data, config)
      .then((response: AxiosResponse<BaseResponse<T>>) => response.data.data)
      .catch((error: AxiosError) => {
        console.error('PUT request failed:', error);
        throw error;
      });
  }

  /**
   * DELETE请求
   * @param url 请求地址
   * @param config 额外配置
   */
  delete<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return axios.delete(url, config)
      .then((response: AxiosResponse<BaseResponse<T>>) => response.data.data)
      .catch((error: AxiosError) => {
        console.error('DELETE request failed:', error);
        throw error;
      });
  }
}

// 创建请求工具实例
export const request = new RequestTool();

export default request;